﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Web.Routing;

namespace MvcPatch
{
    public static class UrlHelperExtensions
    {
        public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action) where TController : Controller
        {
            return Action(helper, action, null);
        }

        public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action, object routeValues) where TController : Controller
        {
            var builder = RouteExpression.Parse(action, helper.RequestContext);

            if (routeValues != null)
            {
                foreach (var pair in new RouteValueDictionary(routeValues))
                {
                    builder.RouteValues.Add(pair.Key, pair.Value);
                }
            }

            var path = builder.GetVirtualPath(helper.RouteCollection, helper.RequestContext);
            if (path == null)
            {
                var actionInfo = RouteExpression.GetActionCall(action).Method;
                string message = String.Format("Url generation failed for {0}", actionInfo);
                throw new ArgumentException(message);
            }

            return path.VirtualPath;
        }

        public static UrlToHelper<TController> To<TController>(this UrlHelper helper) where TController : Controller
        {
            return new UrlToHelper<TController>(helper);
        }
    }
}
